import ezdxf
from ezdxf.addons import Importer


def import_dxf_to_point(src_file, point, des_file):
    sdoc = ezdxf.readfile(src_file)
    tdoc = ezdxf.new('R2010')
    importer = Importer(sdoc, tdoc)
    tblock = tdoc.blocks.new('SOURCE_ENTS')
    ents = sdoc.modelspace().query('CIRCLE LWPOLYLINE DIMENSION LINE ARC INSERT ELLIPSE MTEXT TEXT')
    has_mtext = False
    for e in ents:
        if e.dxftype() == 'MTEXT':
            has_mtext = '微连' in e.text
            break
    # assert has_mtext
    importer.import_entities(ents, tblock)
    importer.finalize()
    msp = tdoc.modelspace()
    msp.add_blockref('SOURCE_ENTS', point)
    tdoc.saveas(des_file)


def import_dxf_all(src_file, des_file):
    sdoc = ezdxf.readfile(src_file)
    tdoc = ezdxf.new('R2010')
    importer = Importer(sdoc, tdoc)
    importer.import_modelspace()
    importer.import_paperspace_layouts()
    importer.finalize()
    tdoc.saveas(des_file)


if __name__ == '__main__':
    # src_file = r"MTEXT_import_missing.dxf"
    src_file = r"C:\Users\YANG.LEI\Downloads\MTEXT_outside.dxf"
    des_block_file = r"imported_block.dxf"
    des_all_file = r"imported_all.dxf"
    import_dxf_to_point(src_file, (-1000, 1000), des_block_file)
    import_dxf_all(src_file, des_all_file)
